import { useKeyPress } from 'ahooks'
import { useDispatch } from 'react-redux'
import { componentAction } from '../../../store/components-reducer'
import { ActionCreators } from 'redux-undo'

export default function useBindCanvasKeyPress() {
  const dispatch = useDispatch()

  useKeyPress(
    ['backspace', 'delete'],
    () => {
      if (!isActiveElementValid()) return
      dispatch(componentAction.removeSelectedComponent())
    },
    { exactMatch: true }
  )

  useKeyPress(
    ['ctrl.c', 'meta.c'],
    () => {
      if (!isActiveElementValid()) return
      dispatch(componentAction.copySelectedComponent())
    },
    { exactMatch: true }
  )

  useKeyPress(
    ['ctrl.v', 'meta.v'],
    () => {
      if (!isActiveElementValid()) return
      dispatch(componentAction.pasteCopiedComponent())
    },
    { exactMatch: true }
  )

  useKeyPress(
    'uparrow',
    () => {
      if (!isActiveElementValid()) return
      dispatch(componentAction.selectPrevComponent())
    },
    { exactMatch: true }
  )

  useKeyPress(
    'downarrow',
    () => {
      if (!isActiveElementValid()) return
      dispatch(componentAction.selectNextComponent())
    },
    { exactMatch: true }
  )

  useKeyPress(
    ['ctrl.z', 'meta.z'],
    () => {
      if (!isActiveElementValid()) return
      dispatch(ActionCreators.undo())
    },
    { exactMatch: true }
  )

  useKeyPress(
    ['ctrl.shift.z', 'meta.shift.z'],
    () => {
      if (!isActiveElementValid()) return
      dispatch(ActionCreators.redo())
    },
    { exactMatch: true }
  )
}

function isActiveElementValid() {
  const { activeElement, body } = document

  if (activeElement === body) return true
  if (activeElement?.matches('div[role="button"]')) return true

  return false
}
